<template>
  <div class="comment-container">
    <van-cell-group>
      <van-field v-model="content"
                 rows="2"
                 autosize
                 label="评论"
                 type="textarea"
                 maxlength="50"
                 placeholder="请输入你的评论"
                 show-word-limit>
        <van-button slot="button"
                    size="small"
                    type="primary"
                    @click="addCmt">发表</van-button>
      </van-field>
    </van-cell-group>
    <section class="cmt van-hairline--bottom"
             v-for="(item, index) in cmtList"
             :key="index">
      <div class="cmt-avatar">
        <img :src="item.user.avatar">
      </div>
      <div class="cmt-main">
        <div class="cmt-author">{{item.user.uname}}</div>
        <p class="cmt-msg">{{item.content}}</p>
        <p class="cmt-time">发表时间：{{item.add_time | dateFormat}}</p>
      </div>
    </section>
  </div>
</template>

<script>
import { Toast } from 'vant'
export default {
  data() {
    return {
      to_id: this.id,
      uid: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user'))._id : '',
      content: '',
      cmtList: []
    }
  },
  created() {
    this.getCmtList()
  },
  methods: {
    // 获取评论列表
    getCmtList() {
      this.axios.get('/cmt/getCmtList', { params: { to_id: this.to_id } }).then(res => {
        if (res.data.code == 1) {
          if (res.data.code == 1) {
            res.data.cmtList.forEach(item => {
              res.data.user.forEach(el => {
                if (item.uid == el._id) {
                  item['user'] = el
                }
              })
              this.cmtList = res.data.cmtList
            })
          }
        }
      })
    },
    // 发表评论
    addCmt() {
      if (this.uid) {
        let params = { content: this.content, to_id: this.to_id, uid: this.uid }
        this.axios.post('/cmt/addCmt', { ...params }).then(res => {
          Toast(res.data.msg)
          this.getCmtList()
        })
        this.content = ''
      } else {
        Toast('登录后才能发表评论哦！')
      }
    }
  },
  props: ['id']
}
</script>

<style lang="scss">
.comment-container {
  padding: 0 0.2rem;
  .cmt {
    display: flex;
    padding: 0.2rem 0;
    .cmt-avatar {
      width: 1.2rem;
      height: 1.2rem;
      flex-shrink: 0;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }
    .cmt-main {
      width: 100%;
      padding: 0 0.3rem;
      .cmt-author {
        font-weight: bold;
      }
      .cmt-time {
        text-align: right;
      }
      p {
        margin: 0;
      }
    }
  }
}
</style>